<template>
	<view style="height: 105vh; background: #181818; position: relative; color: #ffffff;">
		<!--选择日期弹出层-->
		<select-data @queryDataBySelectData='queryDataBySelectData' :show='selectData'
			@closeOrOpenSelectData='closeOrOpenSelectData' />
		<!--选择日期弹出层-->
		<bakc :text="vuex_select_equipment.deviceName" />
		<view class="navigation">
			<view class="select" @click="routeJump('/pages/deviceDetails/deviceDetails')">
				<image class="setting" src="../../static/mecha/detection/setting.png"
					style="width: 35rpx; height:42rpx;" />
				<view style="font-size: 13px; margin-top: 17rpx;">设置</view>
			</view>
			<view class="select" @click="toHistoryPage">
				<image class="setting" src="../../static/icon/timer_inco.png" style="width: 42rpx; height:42rpx;" />
				<view style="font-size: 13px; margin-top: 17rpx;">历史记录</view>
			</view>
		</view>

		<!--传感器-->
		<view class="sensor" v-if="showSensor">
			<view v-for="(item,index) in vuex_select_equipment.mqttValue">
				<view v-if="index == 0" style="display: flex; justify-content: center; align-items: center;">
					<image class="backdrop" :src="obtainChangingBackground(index,item,equipment[index].alarmRange)"
						style="height:440rpx; width: 310px;" />
					<view :class="index == 0 ? 'content': 'content_two'">
						<view style="font-size: 30rpx;">{{ equipment[index].zhName }}
							&nbsp;({{ equipment[index].chemicalName  }})
						</view>
						<view style="display: flex; align-items: center;  margin-left: 60rpx; ">

							<!--离线状态显示-->
							<view style="font-size: 30rpx;"
								v-if="vuex_select_equipment.status == equipmentSatus.offline">
								当前状态:
								{{ '---' }}
							</view>
							<!--在线状态显示-->
							<view style="font-size: 30rpx;" v-else>
								当前状态:
								{{ equipment[index] ? getDangerGrade(item,equipment[index].alarmRange) : '良好' }}
							</view>
							<view class="tip">
								<image @click="toTipsPage(equipment[index].zhName+equipment[index].chemicalName) "
									src="../../static/icon/refer.png" style="width:30rpx; height:30rpx ;" />
							</view>
						</view>
						<view style="height: 15rpx;"></view>
						<view style="font-size: 75rpx; font-weight: 900;">
							{{ vuex_select_equipment.status == equipmentSatus.offline ? '---' : item / equipment[index].reducedUnit }}
						</view>
						<view style="font-size: 26rpx;">
							{{ equipment[index].unit }}
						</view>

					</view>
				</view>

			</view>
		</view>


		<!--日期 图表-->
		<view style="height: 160rpx;"></view>
		<view @click="selectData = true" class="date_table"
			style="display: flex; align-items: center; margin-right: 7px; position: relative; z-index: 9999; "
			v-if="showUchars">
			<view style="font-size: 36rpx; margin-left: 15rpx;">{{ nowDate }}</view>
			<image src="../../static/icon/yellow_bottom_jt.png" style="width:30rpx; height:30rpx; margin-top: 4rpx;" />
		</view>
		<!--uchars 组件-->
		<uchars v-if="showUchars" :categorie='categories' :gasType='gasId' :dataOne='dataOne' :dataTwo='dataTwo'
			:avg='avg' />
		<bar />
	</view>
</template>

<script>
	import {
		searchData
	} from '@/config/api.js';
	export default {
		data() {
			return {

				//选择日期 弹出层控制器变量
				selectData: false,

				showUchars: false,
				showSensor: false,


				//实时数据响应背景
				backdrop: [
					[
						"https://yaolupail.obs.cn-east-3.myhuaweicloud.com:443/hjsbjj/sensor_1.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1735454078&Signature=LOztSC8XQ1/tCuG/ZW2O5bpgwvU%3D",
						"https://yaolupail.obs.cn-east-3.myhuaweicloud.com:443/hjsbjj/sensor_2.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1735454124&Signature=JrPmwZ%2BV6ozA9HyWm4eKqaHhMvY%3D",
						"https://yaolupail.obs.cn-east-3.myhuaweicloud.com:443/hjsbjj/sensor_3.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1735454146&Signature=RYzM9sQnOVuxsQk%2BlUw7ZImIzHg%3D",
						"https://yaolupail.obs.myhuaweicloud.com:443/hjsbjj/sensor_4.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1735523094&Signature=7tnR1y7QS5Z1N0Sn2zvND2iw/cQ%3D"
					],
					[
						"https://yaolupail.obs.cn-east-3.myhuaweicloud.com:443/hjsbjj/sensor_right_one.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1728546181&Signature=jFoO%2BgX/WJp7hlJ%2BC2qDH7M926A%3D",
						"https://yaolupail.obs.cn-east-3.myhuaweicloud.com:443/hjsbjj/sensor_right_two.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1728546194&Signature=bWIGb//5g4k%2Bx9OrIuLixUrWYwk%3D",
						"https://yaolupail.obs.cn-east-3.myhuaweicloud.com:443/hjsbjj/sensor_right_three.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1728546214&Signature=G/Mv//FNsjUK5T2m6z%2BlDveY%2BMU%3D",
						"https://yaolupail.obs.myhuaweicloud.com:443/hjsbjj/right_offline.png?AccessKeyId=LYTX473LFFD5QZN2ZLAR&Expires=1732513342&Signature=l98%2BnR%2BhcghMtEOxdtzGG6oORxo%3D"
					]
				],

				//设备单位数组 里面存储设备信息对象 
				equipment: [],
				//对传感器进行分组
				sensorMap: new Map(),
				//危险等级提示文本
				dangerGradeText: ['轻微污染', '中度污染', '严重污染'],
				//拿到当前的时期
				nowDate: '',
				//查询图表数据的日期单位
				dateUnit: {
					day: "day",
					month: "month",
					year: "year"
				},
				//uchars 组件需要数据
				categories: [],
				dataOne: [],
				dataTwo: [],
				//平均值 
				//甲醛和TVOC的平均值
				avg: [],
				//气体id
				gasId: [],
				equipmentSatus: {
					offline: 1, //离线,
					online: 2, //在线
					newEquipment: 3 //新设备
				},
			}
		},
		onLoad() {
			uni.hideTabBar();
			//隐藏tabBar
			// uni.setTabBarStyle({
			// 	hidden: true
			// })

			//初始化程序
			this.init();
			//vue bus 事件总线加载 detection 页面数据
			this.$bus.$on('loader_detection', (mac) => {
				this.showUchars = false;
				this.showSensor = false;
				//初始化
				setTimeout(() => {
					this.init();
				})

			});
		},

		onReady() {},

		methods: {

			//初始化
			init() {

				//清除数据 单位数据
				this.equipment = [];

				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				// uni.hideTabBar();
				//获取传感器单位名称
				this.getUnitChemicalName();
				//获取到当前时间的月 日
				this.getMonthDay();
				//查询当前设备 当天的数据
				this.getSameDay(new Date());
			},


			//字组件选择日期后 调用该方法查询数据
			queryDataBySelectData(day, month) {
				var newNowData = new Date();
				var queryDate = new Date(newNowData.getFullYear(), month - 1, day)
				this.nowDate = this.formatDateTime(queryDate, "MM月dd日");
				//查询当前设备 当天的数据
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				this.getSameDay(queryDate);
				this.showUchars = false;
				this.selectData = false;

				setTimeout(() => {
					//加载完毕
					this.showUchars = true;
					uni.hideLoading();
				}, 500)
			},

			//选择日期弹出层关闭开启 子组件调用
			closeOrOpenSelectData(openOrColse) {
				this.selectData = openOrColse;
			},

			//根据检测仪的值获取到对于的背景 
			obtainChangingBackground(index, currentValue, dangerNumbers) {

				//先判断设备是否是断线状态
				if (this.vuex_select_equipment.status == this.equipmentSatus.offline) {
					return this.backdrop[index][3];
				}

				let degreeRisk = 0;
				let dangerGrade = this.getDangerGrade(currentValue, dangerNumbers);
				for (var i = 0; i < this.dangerGradeText.length; i++) {
					if (dangerGrade == this.dangerGradeText[i]) {
						degreeRisk = i;
					}
				}
				return this.backdrop[index][degreeRisk];
			},

			//去历史页面
			toHistoryPage() {
				this.routeJump("pages/history/history");
			},

			//跳转到提示页面
			toTipsPage(chemicalName) {
				this.routeJump("pages/tips/tips?chemicalName=" + chemicalName);
			},

			//路由跳转
			routeJump(path) {
				uni.$u.route({
					url: path
				})
			},

			//查询当前设备 当天的数据
			async getSameDay(queryData) {
				// console.log("----------->",this.vuex_select_equipment);
				//请求参数
				let param = {
					date: this.formatDateTime(queryData, "yyyy-MM-dd"),
					timeUnit: this.dateUnit.day,
					eqId: this.vuex_select_equipment.id,
					equipmentMac: this.vuex_select_equipment.mac,
				};
				const resp = await searchData(param);
				let respData = resp.data;
				//图表上显示的时间
				let dataTime = [];

				//曲线数据第一个图表
				let dataNumberOne = [];
				//曲线数据第二个图表
				let dataNumberTwo = [];
				console.log("respData--->", respData);

				if (respData) {
					//获取到时间数据
					for (let item of respData.dates) {
						dataTime.push(item);
					}

					//获取到检测数据1
					for (let item of respData.items[0].data) {
						dataNumberOne.push(item == 0 ? '' : item);
					}

					//获取到检测数据2
					for (let item of respData.items[1].data) {
						dataNumberTwo.push(item == 0 ? '' : item);
					}

					this.gasId[0] = respData.items[0].gasId;
					this.gasId[1] = respData.items[1].gasId;
					this.avg[0] = respData.items[0].avgValue;
					this.avg[1] = respData.items[1].avgValue;
				}

				//组件赋值
				this.categories = dataTime;
				this.dataOne = dataNumberOne;
				this.dataTwo = dataNumberTwo;
			},

			//获取当前日期的 月日
			getMonthDay() {
				this.nowDate = this.formatDateTime(new Date(), "MM月dd日");
			},

			//自定义格式化
			formatDateTime(date, format) {
				const o = {
					'M+': date.getMonth() + 1, // 月份
					'd+': date.getDate(), // 日
					'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
					'H+': date.getHours(), // 小时
					'm+': date.getMinutes(), // 分
					's+': date.getSeconds(), // 秒
					'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
					S: date.getMilliseconds(), // 毫秒
					a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
					A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
				};
				if (/(y+)/.test(format)) {
					format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
				}
				for (let k in o) {
					if (new RegExp('(' + k + ')').test(format)) {
						format = format.replace(
							RegExp.$1,
							RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
						);
					}
				}
				return format;
			},

			//获取到危险等级
			getDangerGrade(currentValue, dangerNumbers) {
				let list = dangerNumbers.split(":");
				for (var i = 0; i < list.length; i++) {
					if (currentValue < parseInt(list[i])) {
						return this.dangerGradeText[i]; //危险等级 0 良好 1  警告 2 超标
					}
				}
				//如果全部都是大于就是最危险的等级
				return this.dangerGradeText[2];
			},

			//获取传感器单位和化学名
			getUnitChemicalName() {
				//获取到当前设备传感器id
				let gasIds = this.vuex_select_equipment.sensor.gasId.split(':');
				//获取到所有的传感器
				let gas = this.vuex_select_equipment.gas;
				for (let item of gas) {
					this.sensorMap.set(item.id, item);
				}
				//获取到当前传感器对于的单位化学名
				for (let item of gasIds) {
					let sensorObj = this.sensorMap.get(parseInt(item));
					this.equipment.push(sensorObj);
				}
				//把单位存储到vuex 中
				let select_equipment = this.vuex_select_equipment;
				this.$set(select_equipment, 'sensorType', this.equipment);
				this.$u.vuex('vuex_select_equipment', select_equipment)

				//把单位存储到新配网的 vuex 中
				let new_equipment = this.vuex_new_equipment;
				this.$set(new_equipment, 'sensorType', this.equipment);
				this.$u.vuex('vuex_new_equipment', new_equipment)

				setTimeout(() => {
					//加载完毕
					this.showUchars = true;
					this.showSensor = true;
					uni.hideLoading();
				}, 2000)
			},




		}
	}
</script>

<style lang="scss" scoped>
	.tip {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.navigation {
		position: relative;
		width: 100%;
		height: 130rpx;
		margin-top: 2rpx;
		display: flex;
		justify-content: space-between;

		.select {
			width: 49.82%;
			height: 56px;
			background: rgb(53, 53, 53);
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			padding-top: 10rpx;
			padding-bottom: 10rpx;
		}

	}

	.sensor {
		// display: flex;
		// justify-content: space-between;
		width: 100%;
		height: 330rpx;
		position: relative;

		.content {
			display: flex;
			flex-direction: column;
			align-items: center;
			position: absolute;
			font-size: 40rpx;
		}

		.content_two {
			display: flex;
			flex-direction: column;
			align-items: center;
			position: absolute;
			top: 50rpx;
			right: 40rpx;
			font-size: 40rpx;
		}
	}


	.date_table {
		width: 100%;
		margin-right: 30rpx;
		font-size: 42rpx;
		margin-left: 15rpx;
		position: relative;
	}

	.history {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: absolute;
		right: 110rpx;
		top: -20rpx;
		font-size: 12px;
	}
</style>